(function() {
    var jQUi;

    //Check to see if any <nav> items are found. If so, add the CSS classes
    jq(document).ready(function() {
        if (jq("nav").length > 0) {
            jq("#jQUi #header").addClass("hasMenu");
            jq("#jQUi #content").addClass("hasMenu");
            jq("#jQUi #navbar").addClass("hasMenu");
        }
        jQUi = jq("#jQUi");
        setTimeout(function(){
        hideAddressBar();
        },100);
    });
    
    document.addEventListener("appMobi.device.ready", function() { //in AppMobi, we need to undo the height stuff since it causes issues.
        setTimeout(function() {
            jQUi.css("height", "100%"), document.body.style.height = "100%";
            document.documentElement.style.minHeight = window.innerHeight;
        }, 300);
    });
    
    
    window.addEventListener("orientationchange", function(e) {
        //jq.ui.updateOrientation()
        window.setTimeout(function() {
            hideAddressBar();
        }, 200);
    }, false);
    
    if (jq.os.android) 
    {
        window.addEventListener("resize", function(e) {
            window.scrollTo(0,1);            
            // jq.ui.updateOrientation();
            if(document.body.clientWidth>=700)
               // $.ui.toggleSideMenu(false);
            window.setTimeout(function() {
                hideAddressBar();
            }, 100);
        }, false);
    }
    
    
    function hideAddressBar() {
        if (jq.os.desktop)
            return jQUi.css("height", "100%");
        if (jq.os.android) {
            window.scrollTo(1, 1);
            if (document.documentElement.scrollHeight < window.outerHeight / window.devicePixelRatio)
                jQUi.css("height", (window.outerHeight / window.devicePixelRatio) + 'px');
        } 
        else {
            document.documentElement.style.height = "5000px";
            
            window.scrollTo(0, 1);
            document.documentElement.style.height = window.innerHeight + "px";
            jQUi.css("height", window.innerHeight + "px");
        }
    }
    //The following is based on Cubiq.org - iOS no click delay.  We use this to capture events to input boxes to fix Android...and fix iOS ;)
    //We had to make a lot of fixes to allow access to input elements on android, etc.
    function NoClickDelay(el) {
        if (typeof (el) === "string")
            el = document.getElementById(el);
        el.addEventListener('touchstart', this, true);
    }
    var prevClickField;
    var prevPanel;
    var prevField;
    NoClickDelay.prototype = {
        dX: 0,
        dY: 0,
        cX: 0,
        cY: 0,
        handleEvent: function(e) {
            switch (e.type) {
                case 'touchstart':
                    this.onTouchStart(e);
                    break;
                case 'touchmove':
                    this.onTouchMove(e);
                    break;
                case 'touchend':
                    this.onTouchEnd(e);
                    break;
            }
        },
        
        onTouchStart: function(e) {
            
            this.dX = e.touches[0].pageX;
            this.dY = e.touches[0].pageY;

            var theTarget = e.target;
            if (theTarget.nodeType == 3)
                theTarget = theTarget.parentNode;
            
            if(prevField){
                prevField.blur();
                prevField=null;
            }
            if(prevPanel){
                //prevField.blur();
                prevPanel.css("-webkit-transform","translate3d(0px,0px,0px)");
                prevPanel.css("left","0");
                prevField=null;
                prevPanel=null;
            }
            
            var tagname = theTarget.tagName.toLowerCase();
            var type=theTarget.type||"";
            if((tagname=="a"&& theTarget.href.indexOf("tel:")===0)||((tagname=="input")||tagname=="textarea"||tagname=="select")){
                prevField=theTarget;
                if(jq.os.android&&$.ui.fixAndroidInputs){
                    theTarget.focus();
                    prevField=theTarget;
                    prevPanel=$(theTarget).closest(".panel");
                    prevPanel.css("left","-100%");
                    prevPanel.css("-webkit-transition-duration","0ms");
                    prevPanel.css("-webkit-transform","translate3d(100%,0px,0px)");
                    prevPanel.css("position","absolute");
                    return;
                }
            }
            else
                e.preventDefault();
            this.moved = false;
            document.addEventListener('touchmove', this, true);
            document.addEventListener('touchend', this, true);
        },
        
        onTouchMove: function(e) {
            this.moved = true;
            this.cX = e.touches[0].pageX - this.dX;
            this.cY = e.touches[0].pageY - this.dY;
           // e.preventDefault();
        },
        
        onTouchEnd: function(e) {
            
            document.removeEventListener('touchmove', this, false);
            document.removeEventListener('touchend', this, false);
            
            if ((!jq.os.blackberry && !this.moved) || (jq.os.blackberry && (Math.abs(this.cX) < 5 || Math.abs(this.cY) < 5))) {
                var theTarget = e.target;
                if (theTarget.nodeType == 3)
                    theTarget = theTarget.parentNode;
                
                var theEvent = document.createEvent('MouseEvents');
                theEvent.initEvent('click', true, true);
                theTarget.dispatchEvent(theEvent);
                
            }
            prevClickField = null;
            this.dX = this.cX = this.cY = this.dY = 0;
        }
    };
    
    
    
    jq(document).ready(function() {
        document.body.addEventListener('touchmove', function(e) {
            e.preventDefault();
            e.stopPropagation();
            window.scrollTo(1, 1);
        }, false);
        if (!jq.os.desktop)
            new NoClickDelay(document.getElementById("jQUi"));
            
        document.getElementById("jQUi").addEventListener("click", function(e) {
            
            var theTarget = e.target;
            if (theTarget.nodeType == 3)
                theTarget = theTarget.parentNode;
                
            if (checkAnchorClick(theTarget)) {
                e.preventDefault();
                return false;
            }
        }, true);
        
        jq("#navbar").on("click", "a", function(e) {
            jq("#navbar a").removeClass("selected");
            setTimeout(function() {
                $(e.target).addClass("selected");
            }, 10);
        });
    });
    
    function checkAnchorClick(theTarget) {
        var parent = false;
        if (theTarget.tagName.toLowerCase() != "a" && theTarget.parentNode)
            parent = true, theTarget = theTarget.parentNode; //let's try the parent so <a href="#foo"><img src="whatever.jpg"></a> will work
        if (theTarget.tagName.toLowerCase() == "a") {
        
        
            var custom=(typeof jq.ui.customClickHandler=="function")?jq.ui.customClickHandler:false;
            if(custom!==false&&jq.ui.customClickHandler(theTarget.href)){
               return true;
            }
            if (theTarget.href.toLowerCase().indexOf("javascript:") !== -1 || theTarget.getAttribute("data-ignore")) {
                return false;
            }
            
            if (theTarget.onclick && !jq.os.desktop) {
                theTarget.onclick();
            }
            
            if(theTarget.href.indexOf("tel:")===0)
               return false;
            if (theTarget.hash.indexOf("#") === -1 && theTarget.target.length > 0) 
            {
                
                if (theTarget.href.toLowerCase().indexOf("javascript:") != 0) {
                    if (jq.ui.isAppMobi)
                        AppMobi.device.launchExternal(theTarget.href);
                    else if (!jq.os.desktop)
                        brokerClickEventMobile(theTarget);
                    else
                        window.open(theTarget);
                    return true;
                }
                return false;
            }
            if ((theTarget.href.indexOf("#") !== -1 && theTarget.hash.length == 0) || theTarget.href.length == 0)
                return true;
			
            var mytransition = theTarget.getAttribute("data-transition");
            var resetHistory = theTarget.getAttribute("data-resetHistory");
            
            resetHistory = resetHistory && resetHistory.toLowerCase() == "true" ? true : false;
            
            var href = theTarget.hash.length > 0 ? theTarget.hash : theTarget.href;
			
	    //add dialog support anchor.	
		if (theTarget.getAttribute("data-dialog") == "true") {
		  var title = theTarget.childNodes[0].nodeValue ;
		  var confirmScript = theTarget.getAttribute("onconfirm");
		  jq.ui.openDialog(href,confirmScript,title);
		  return true;
		}
			
            jq.ui.loadContent(href, resetHistory, 0, mytransition, theTarget);
            return true;
        }
    }
    function brokerClickEventMobile(theTarget) {
        if (jq.os.desktop)
            return;
        var clickevent = document.createEvent('Event');
        clickevent.initEvent('click', true, false);
        theTarget.target = "_blank";
        theTarget.dispatchEvent(clickevent);
    }
})();